package com.herui.iot.ui.evaluation.execute;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.herui.device_lib.listener.DeviceLis;
import com.herui.device_lib.listener.DeviceLisAdapter;
import com.herui.device_lib.presenter.DevicePresenter;
import com.herui.device_lib.presenter.DevicePresenterInter;
import com.herui.device_lib.presenter.SimDevicePresenter;
import com.herui.sdyu_lib.http.callback.Callback;
import com.herui.sdyu_lib.utils.StringUtils;
import com.herui.sdyu_lib.utils.ToastUtil;
import com.herui.sport_care.BaseView;
import com.herui.sport_care.data.check.AgreementDetailResponse;
import com.herui.sport_care.data.check.AgreementResponse;
import com.herui.sport_care.data.check.BetaDataFileUploadRequest;
import com.herui.sport_care.data.check.EvaluationStage;
import com.herui.sport_care.data.eval.EvalInfo;
import com.protontek.healthy.powerbicyclesdkcore.api.PowerBicycleDataBean;
import com.protontek.healthy.sdkcore.sphygmomanometer.api.BPDataBean;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by amanda.shan on 2022/12/9.
 */
public class PowerExecutePresenter extends BaseExecutePresenter {

    static String TAG = "PowerExecutePresenter";

    SimpleDateFormat format = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss");

    ExecutorService executorService = Executors.newSingleThreadExecutor();

    public static interface View extends BaseView, DeviceLis {
        // 回调阶段名称
        default void onStage(EvaluationStage stage) {
        }

        // 回调经过的时间
        default void onTime(int second) {
        }

        //回调协议
        default void onAgreementResponse(AgreementResponse agreementResponse) {
        }

        // 完成所有
        default void finish() {
        }
    }

    // 协议详细信息
    private AgreementResponse agreementResponse;

    private View view;

    private Timer timer;
    private Long startTime;     // 小阶段的开始时间
    private List<AgreementDetailResponse> agreementDetailList;  // 每个阶段的控制流程
    private int index;  // 阶段序号
    private boolean upFlag = false;


    public PowerExecutePresenter(View view, EvalInfo evalInfo) {
        super(evalInfo);
        this.view = view;
    }

    @Override
    public void start() {
        getAgreement(evalInfo.getAgreementId());
        DeviceLisAdapter.add(deviceLis);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (stage != null && agreementDetailList != null && index < agreementDetailList.size()) {
                    int d = (int) ((System.currentTimeMillis() - startTime) / 1000);
                    AgreementDetailResponse agreementDetailResponse =
                            agreementDetailList.get(index);
                    // 发送新的阻力
                    if (d >= agreementDetailResponse.getDuration()) {
                        agreementDetailResponse = agreementDetailList.get(index++);
                        int r = agreementDetailResponse.getResistance().intValue();
                        devicePresenter.setResistanceLevel(r);
                        startTime = System.currentTimeMillis();
                    }
                }

                if (stage != null) {
                    view.onTime((int) ((System.currentTimeMillis() - stageStartTime) / 1000));
                }

                // 恢复阶段
                if (stage != null && stage.equals(EvaluationStage.RECOVER)) {
                    recoverProcess();
                }

                if (upFlag) {
                    upload(false);
                }
            }
        }, 0, 1000);
    }

    public void stop() {
        DeviceLisAdapter.remove(deviceLis);
        timer.cancel();
        devicePresenter.disConnectAll();
    }

    // 下一步
    public void next() throws IOException {
        executorService.execute(new Runnable() {
            @Override
            public void run() {

                // 判断是否进行下一步
                if (agreementDetailList != null && index < agreementDetailList.size()) {
                    ToastUtil.showMessage("当前阶段还未完成无法下一步");
                    return;
                }

                if (agreementDetailList != null && index >= agreementDetailList.size()
                        && startTime != null && agreementDetailList.size() > 0) {
                    AgreementDetailResponse agreementDetailResponse =
                            agreementDetailList.get(agreementDetailList.size() - 1);
                    int d = (int) ((System.currentTimeMillis() - startTime) / 1000);
                    if (agreementDetailResponse.getDuration()==null){
                        Log.d(TAG, "next: 当前阶段没有设置持续时长");
                    } else if (d < agreementDetailResponse.getDuration()) {
                        ToastUtil.showMessage("当前阶段还未完成无法下一步");
                        return;
                    }
                }

                if (stage == null) {
                    clearData();
                    try {
                        nextOk();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else if (stage == EvaluationStage.WARM_UP) {
                    uploadAll();
                } else if (stage == EvaluationStage.TESTING) {
                    uploadAll();
                } else if (stage == EvaluationStage.RECOVER) {
                    uploadAll();
                }
            }
        });
    }

    /**
     * 下一步成功
     *
     * @throws IOException
     */
    public void nextOk() throws IOException {

        handler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    upFlag = true;
                    if (stage == null) {
                        // 热身阶段
                        sportFileManager.initEcgStore(evalUserInfo.getUserId().intValue(),
                                evalInfo.getEvaluationSchemeId().intValue(),
                                EvaluationStage.WARM_UP);
                        agreementDetailList = agreementResponse.getWarmUpAgreementDetailList();
                        stage = EvaluationStage.WARM_UP;
                        clearData();
                    } else if (stage == EvaluationStage.WARM_UP) {
                        sportFileManager.initEcgStore(evalUserInfo.getUserId().intValue(),
                                evalInfo.getEvaluationSchemeId().intValue(),
                                EvaluationStage.TESTING);
                        agreementDetailList = agreementResponse.getIncreaseAgreementDetailList();
                        stage = EvaluationStage.TESTING;
                        clearData();
                    } else if (stage == EvaluationStage.TESTING) {
                        sportFileManager.initEcgStore(evalUserInfo.getUserId().intValue(),
                                evalInfo.getEvaluationSchemeId().intValue(),
                                EvaluationStage.RECOVER);
                        agreementDetailList = agreementResponse.getRecoverAgreementDetailList();
                        stage = EvaluationStage.RECOVER;
                        clearData();
                    } else if (stage == EvaluationStage.RECOVER) {
                        // 完成测试
                        view.finish();
                    }

                    startTime = System.currentTimeMillis();
                    stageStartTime = System.currentTimeMillis();

                    index = 0;
                    // 发送阻力
                    if (agreementDetailList.size() > 0) {
                        AgreementDetailResponse agreementDetailResponse =
                                agreementDetailList.get(index++);
                        devicePresenter.setResistanceLevel(agreementDetailResponse.getResistance().intValue());
                    }

                    view.onStage(stage);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * 上传文件和数据到服务器
     *
     * @return
     */
    private boolean uploadAll() {
        upFlag = false;
        Long evaluationSchemeId = evalInfo.getEvaluationSchemeId();
        int userId = evalUserInfo.getUserId().intValue();
        try {
            sportFileManager.saveHeart(userId, evaluationSchemeId.intValue(), hearts);
        } catch (IOException e) {
            e.printStackTrace();
            ToastUtil.showMessage("保存心率数据失败");
            return false;
        }

        try {
            sportFileManager.closeEcgStore();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String ecgPath = sportFileManager.uploadEcg(evalUserInfo.getUserId().intValue(),
                evaluationSchemeId.intValue(), stage);
        if (StringUtils.isEmpty(ecgPath)) {
            ToastUtil.showMessage("上传心电数据失败");
            return false;
        }
        String heartPath = sportFileManager.uploadHeart(evalUserInfo.getUserId().intValue(),
                evaluationSchemeId.intValue());
        if (StringUtils.isEmpty(heartPath)) {
            ToastUtil.showMessage("上传心率数据失败");
            return false;
        }

        try {
            sportFileManager.saveResistance(userId, evaluationSchemeId.intValue(), resistances);
        } catch (IOException e) {
            e.printStackTrace();
            ToastUtil.showMessage("保存阻力数据失败");
            return false;
        }
        String rPath = sportFileManager.uploadResistance(userId, evaluationSchemeId.intValue());
        if (StringUtils.isEmpty(rPath)) {
            ToastUtil.showMessage("上传阻力数据失败");
            return false;
        }

        // 上传文件路径
        BetaDataFileUploadRequest betaDataFileUploadRequest = new BetaDataFileUploadRequest();
        betaDataFileUploadRequest.setBeEvaluatedId(evalUserInfo.getUserId());
        betaDataFileUploadRequest.setEvaluationSchemeId(evaluationSchemeId);
        switch (stage) {
            case WARM_UP:
                betaDataFileUploadRequest.setWarmUpEcgFileUrl(ecgPath);
                betaDataFileUploadRequest.setWarmUpHeartRateTrendFileUrl(heartPath);
                betaDataFileUploadRequest.setWarmUpPowerTrendFileUrl(rPath);
                break;
            case TESTING:
                betaDataFileUploadRequest.setTestingEcgFileUrl(ecgPath);
                betaDataFileUploadRequest.setTestingHeartRateTrendFileUrl(heartPath);
                betaDataFileUploadRequest.setTestingPowerTrendFileUrl(rPath);
                break;
            case RECOVER:
                betaDataFileUploadRequest.setRecoverEcgFileUrl(ecgPath);
                betaDataFileUploadRequest.setRecoverHeartRateTrendFileUrl(heartPath);
                betaDataFileUploadRequest.setRecoverPowerTrendFileUrl(rPath);
                break;
        }
        checkSource.fileDataUpload(betaDataFileUploadRequest,
                new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d(TAG, "onSuccess: 上传文件路径成功" + JSON.toJSONString(betaDataFileUploadRequest));
                upload(true);
            }

            @Override
            public void onError(Throwable e, String code, String message) {
                processError(e, code, message);
            }
        });

        return true;
    }

    @Override
    protected void dataUploadSucess(Boolean uploadAll) {
        if (uploadAll) {
            try {
                nextOk();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 上传数据
    private void upload(boolean isUploadAll) {
        if (stage == null) {
            return;
        }
        // 热身
        if (stage.equals(EvaluationStage.WARM_UP)) {
            warnUpDataUp(isUploadAll);
        }

        // 测试
        if (stage.equals(EvaluationStage.TESTING)) {
            testDataUp(isUploadAll);
        }

        // 恢复
        if (stage.equals(EvaluationStage.RECOVER)) {
            recoverDataUp(isUploadAll);
        }
    }


    /**
     * 获取协议详情
     *
     * @param agreementId
     */
    public void getAgreement(Long agreementId) {
        checkSource.getAgreement(agreementId, new Callback.CommonCallback<AgreementResponse>() {
            @Override
            public void onSuccess(AgreementResponse result) {
                agreementResponse = result;
                view.onAgreementResponse(agreementResponse);
            }

            @Override
            public void onError(Throwable e, String code, String message) {
                processError(e, code, message);
            }
        });
    }

    protected DeviceLis deviceLis = new DeviceLis() {

        @Override
        public void onConnectEcg(boolean flag) {
            handler.post(() -> {
                view.onConnectEcg(flag);
            });
        }

        @Override
        public void onConnectSpo(boolean flag) {
            handler.post(() -> {
                view.onConnectSpo(flag);
            });
        }

        @Override
        public void onConnectBicycle(boolean flag) {
            handler.post(() -> {
                view.onConnectBicycle(flag);
            });
        }

        @Override
        public void onBpResult(BPDataBean bpDataBean) {
            handler.post(() -> {
                baseDeviceLis.onBpResult(bpDataBean);
                view.onBpResult(bpDataBean);
            });
        }

        @Override
        public void onReceiveSpO2(int spo) {
            handler.post(() -> {
                baseDeviceLis.onReceiveSpO2(spo);
                view.onReceiveSpO2(spo);
            });
        }

        @Override
        public void onEcgHeart(int heart) {
            handler.post(() -> {
                baseDeviceLis.onEcgHeart(heart);
                view.onEcgHeart(heart);
            });
        }

        @Override
        public void onEcgData(byte[] bytes) {
            handler.post(() -> {
                baseDeviceLis.onEcgData(bytes);
                view.onEcgData(bytes);
            });
        }

        @Override
        public void onReceiveData(PowerBicycleDataBean powerBicycleDataBean) {
            handler.post(() -> {
                baseDeviceLis.onReceiveData(powerBicycleDataBean);
                view.onReceiveData(powerBicycleDataBean);
            });
        }
    };

    @Override
    public BaseView getView() {
        return view;
    }

}
